<template>
  <div class="forgot-container">
    <div class="forgot-box">
      <div class="forgot-title">找回密码</div>
      <el-form :model="form" :rules="rules" ref="formRef" class="forgot-form">
        <el-form-item prop="phone">
          <el-input
            v-model="form.phone"
            placeholder="请输入手机号"
            :prefix-icon="Cellphone"
            size="large"
            maxlength="11"
            @blur="checkPhone"
          />
        </el-form-item>
        <el-form-item prop="code">
          <el-row :gutter="8" style="width: 100%">
            <el-col :span="16">
              <el-input
                v-model="form.code"
                placeholder="请输入验证码"
                :prefix-icon="Message"
                size="large"
                maxlength="6"
              />
            </el-col>
            <el-col :span="8">
              <el-button
                :disabled="countdown > 0"
                size="large"
                @click="sendCode"
                style="width: 100%"
              >
                <span v-if="countdown === 0">获取验证码</span>
                <span v-else>{{ countdown }}s</span>
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入新密码"
            :prefix-icon="Lock"
            size="large"
            show-password
          />
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="form.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            :prefix-icon="Lock"
            size="large"
            show-password
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="large" class="forgot-btn" @click="onSubmit"
            >重置密码</el-button
          >
        </el-form-item>
      </el-form>
      <div class="back-login">
        <el-link type="primary" @click="goLogin">返回登录</el-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Cellphone, Message, Lock } from '@element-plus/icons-vue'
import {forgotPassword, onRepeatPhone, phone} from "@/assets/user.js";

const router = useRouter()
const form = ref({
  phone: '',
  code: '',
  password: '',
  confirmPassword: '',
})
const rules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码为6位数字', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码至少6位', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value) => value === form.value.password,
      message: '两次输入密码不一致',
      trigger: 'blur',
    },
  ],
}
const formRef = ref(null)

const countdown = ref(0)
let timer = null
const sendCode = async () => {
  if (!/^1[3-9]\d{9}$/.test(form.value.phone)) {
    ElMessage.error('请输入正确的手机号')
    return
  }
  
  try {
    const res = await phone(form.value.phone)
    if (res.data.code === 200) {
      ElMessage.success('验证码已发送！')
      countdown.value = 60
      timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
          timer = null
        }
      }, 1000)
    } else {
      ElMessage.error(res.data.message || '验证码发送失败')
    }
  } catch (error) {
    ElMessage.error('验证码发送失败，请重试')
  }
}
//定义检查手机号是否存在
const checkPhone = async () => {
  const res = await onRepeatPhone({ phone: form.value.phone });
  console.log(res.data.code);
  console.log(res.data);
  if (res.data.code === 400) {
    ElMessage.error('请确认该手机号是否为您账号所绑定的手机号');
  }

}
const onSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 这里应调用后端接口重置密码，成功后跳转
      forgotPassword(form.value).then(res=>{
        if(res.data.code==200){
          ElMessage.success('密码重置成功！即将跳转登录...')
          setTimeout(() => {
            router.push({
              path: '/',
              query: {
                username: form.value.phone,
                password: form.value.password,
              },
            })
          }, 1200)
        }else{
          ElMessage.success(res.data.message)
        }
      })
    }
  })
}
const goLogin = () => {
  router.push('/')
}

</script>

<style scoped>
.forgot-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(120deg, #2980b9 0%, #6dd5fa 100%);
}
.forgot-box {
  background: #fff;
  padding: 48px 40px 32px 40px;
  border-radius: 16px;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.2);
  min-width: 360px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.forgot-title {
  font-size: 2rem;
  font-weight: bold;
  color: #2980b9;
  margin-bottom: 32px;
  letter-spacing: 2px;
}
.forgot-form {
  width: 100%;
  margin-top: 24px;
}
.forgot-btn {
  width: 100%;
  font-size: 1.1rem;
  letter-spacing: 1px;
}
.back-login {
  margin-top: 12px;
  text-align: right;
  width: 100%;
}
</style>
